package com.teamone.etl.apimanager.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.teamone.etl.apimanager.dao.ApiDao;
import com.teamone.etl.apimanager.dao.ApiSourceDao;
import com.teamone.etl.apimanager.dao.ApiTypeDao;
import com.teamone.etl.apimanager.entity.ApiType;
import com.teamone.etl.apimanager.request.BaseQuery;
import com.teamone.etl.apimanager.service.ApiTypeService;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import static com.teamone.etl.constant.EtlConstant.Api.*;

/**
 * 接口类型表(ApiType)表服务实现类
 *
 * @author makejava
 * @since 2021-01-20 18:32:06
 */
@Service("apiTypeService")
@Transactional(rollbackFor = Exception.class)
public class ApiTypeServiceImpl extends ServiceImpl<ApiTypeDao, ApiType> implements ApiTypeService {

    @Resource
    private ApiDao apiDao;
    @Resource
    private ApiSourceDao apiSourceDao;

    @Override
    public PageInfo<ApiType> selectAll(BaseQuery baseQuery) {
        PageHelper.startPage(baseQuery.getPageNum(),baseQuery.getPageSize());
        List<ApiType> apiTypes = baseMapper.selectAll();
        List<Map<String,Object>> apiAmounts= apiSourceDao.selectApiAmountGroupByApiTypeId();
        List<Map<String,Object>> totalUses= apiDao.selectTotalUsesGroupByApiTypeId();
        apiTypes.forEach(apiType -> {
            apiAmounts.forEach(maps->{
                if (maps.get(API_TYPE_ID).equals(apiType.getId())) {
                    apiType.setApiAmount(Long.parseLong(maps.get(API_AMOUNT).toString()));
                }
            });
            totalUses.forEach(maps->{
                if (maps.get(API_TYPE_ID).equals(apiType.getId())) {
                    apiType.setTotalUse(Long.valueOf(maps.get(TOTAL_USE).toString()));
                }
            });
        });
        return new PageInfo<>(apiTypes);
    }

    @Override
    public void logicDeleteById(Integer id) {
        baseMapper.logicDeleteById(id);
        apiSourceDao.logicDeleteByApiTypeId(id);
        apiDao.logicDeleteByApiTypeId(id);
    }

    @Override
    public void updateOne(ApiType apiType) {
        baseMapper.updateOne(apiType);
    }

    @Override
    public void saveOne(ApiType apiType) {
        baseMapper.saveOne(apiType);
    }
}